import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Space, Tag, message, Select, Input, Image, Tooltip, Dropdown, Modal, Row, Col, Statistic } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, CheckCircleOutlined, StopOutlined, MoreOutlined } from '@ant-design/icons';
import PromotionDetail from './PromotionDetail';
import usePromotionsStore from '../../store/promotions/usePromotionsStore';

const { Search } = Input;
const { Option } = Select;

const PromotionsList = () => {
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentPromotion, setCurrentPromotion] = useState(null);
  
  const {
    promotions,
    loading,
    filters,
    getPromotions,
    deletePromotion,
    togglePromotionStatus,
    setFilters
  } = usePromotionsStore();

  useEffect(() => {
    getPromotions();
  }, []);

  const handleAdd = () => {
    setCurrentPromotion(null);
    setDetailVisible(true);
  };

  const handleEdit = (record) => {
    setCurrentPromotion(record);
    setDetailVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      await deletePromotion(id);
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleDetailClose = () => {
    setDetailVisible(false);
    setCurrentPromotion(null);
    getPromotions(filters);
  };

  const handleStatusChange = async (id, status) => {
    try {
      await togglePromotionStatus(id, status);
      message.success('状态更新成功');
    } catch (error) {
      message.error('状态更新失败');
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 60,
      align: 'center',
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 180,
      render: (text) => (
        <span style={{ fontWeight: 500 }}>{text}</span>
      ),
    },
    {
      title: 'Slug',
      dataIndex: 'slug',
      key: 'slug',
      width: 180,
      render: (slug) => (
        <Tag color="cyan" style={{ fontSize: 12 }}>{slug}</Tag>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type) => (
        <Tag color={type === 'banner' ? 'blue' : 'green'}>
          {type.toUpperCase()}
        </Tag>
      ),
    },
    {
      title: '图片',
      dataIndex: 'image',
      key: 'image',
      width: 120,
      render: (image) => (
        <Image
          src={image}
          alt="推广图片"
          width={100}
          height={50}
          style={{ objectFit: 'cover', borderRadius: 4 }}
          preview={{
            mask: '预览'
          }}
        />
      ),
    },
    {
      title: '链接',
      dataIndex: 'linkUrl',
      key: 'linkUrl',
      width: 250,
      render: (url, record) => (
        <div style={{ width: '100%' }}>
          <Tag color={record.linkType === 'internal' ? 'blue' : 'orange'} style={{ marginBottom: 4 }}>
            {record.linkType === 'internal' ? '内链' : '外链'}
          </Tag>
          <Tooltip title={url} placement="topLeft">
            <div style={{ 
              fontSize: 12, 
              color: '#666',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              cursor: 'pointer'
            }}>
              {url}
            </div>
          </Tooltip>
        </div>
      ),
    },
    {
      title: '权重',
      dataIndex: 'weight',
      key: 'weight',
      width: 80,
      align: 'center',
      sorter: (a, b) => a.weight - b.weight,
      render: (weight) => (
        <Tag color="default">{weight}</Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={status === 'active' ? 'success' : 'default'}>
          {status === 'active' ? '已上线' : '已下线'}
        </Tag>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 180,
      render: (date) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 80,
      align: 'center',
      fixed: 'right',
      render: (_, record) => {
        const items = [
          {
            key: 'edit',
            label: '编辑',
            icon: <EditOutlined />,
            onClick: () => handleEdit(record),
          },
          {
            key: 'status',
            label: record.status === 'active' ? '下线' : '上线',
            icon: record.status === 'active' ? <StopOutlined /> : <CheckCircleOutlined />,
            onClick: () => handleStatusChange(record.id, record.status === 'active' ? 'inactive' : 'active'),
          },
          {
            type: 'divider',
          },
          {
            key: 'delete',
            label: '删除',
            icon: <DeleteOutlined />,
            danger: true,
            onClick: () => {
              Modal.confirm({
                title: '确定要删除这个推广吗？',
                content: '删除后将无法恢复',
                onOk: () => handleDelete(record.id),
                okText: '确定',
                cancelText: '取消',
              });
            },
          },
        ];

        return (
          <Dropdown
            menu={{ items }}
            trigger={['click']}
            placement="bottomRight"
          >
            <Button
              type="text"
              icon={<MoreOutlined />}
              style={{ fontSize: 20 }}
            />
          </Dropdown>
        );
      },
    },
  ];

  // 计算统计数据
  const statistics = {
    total: promotions.length,
    active: promotions.filter(p => p.status === 'active').length,
    inactive: promotions.filter(p => p.status === 'inactive').length,
    banner: promotions.filter(p => p.type === 'banner').length,
    splash: promotions.filter(p => p.type === 'splash').length,
  };

  return (
    <>
      <div className="p-6">
        <Row gutter={16} className="mb-6">
          <Col span={6}>
            <Card>
              <Statistic
                title="全部推广"
                value={statistics.total}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="已上线"
                value={statistics.active}
                valueStyle={{ color: '#3f8600' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="已下线"
                value={statistics.inactive}
                valueStyle={{ color: '#cf1322' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="Banner / Splash"
                value={`${statistics.banner} / ${statistics.splash}`}
              />
            </Card>
          </Col>
        </Row>

        <Card>
          <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16 }}>
            <Space size={12}>
              <Select
                style={{ width: 140 }}
                value={filters.status}
                onChange={(value) => setFilters({ status: value })}
                placeholder="状态筛选"
              >
                <Option value="all">全部</Option>
                <Option value="active">已上线</Option>
                <Option value="inactive">已下线</Option>
              </Select>
              <Select
                style={{ width: 120 }}
                value={filters.type}
                onChange={(value) => setFilters({ type: value })}
                placeholder="类型筛选"
              >
                <Option value="all">全部类型</Option>
                <Option value="banner">Banner</Option>
                <Option value="splash">Splash</Option>
              </Select>
              <Search
                placeholder="搜索名称、描述或Slug"
                style={{ width: 300 }}
                value={filters.searchText}
                onChange={(e) => setFilters({ searchText: e.target.value })}
                onSearch={(value) => setFilters({ searchText: value })}
                allowClear
              />
            </Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              新增推广
            </Button>
          </div>

          <Table
            columns={columns}
            dataSource={promotions}
            rowKey="id"
            loading={loading}
            pagination={{
              showSizeChanger: true,
              showTotal: (total) => `共 ${total} 条`,
              defaultPageSize: 10,
              pageSizeOptions: ['10', '20', '50', '100'],
            }}
            scroll={{ x: 1400 }}
          />
        </Card>
      </div>

      <PromotionDetail
        visible={detailVisible}
        onClose={handleDetailClose}
        promotion={currentPromotion}
      />
    </>
  );
};

export default PromotionsList;